package com.bupt.service;

import com.bupt.bean.ChannelSection;
import com.bupt.bean.DeviceChannel;
import com.bupt.config.CommonCode;
import com.bupt.config.Result;
import com.bupt.config.SectionResult;
import com.bupt.dao.DeviceChannelRepository;
import com.bupt.dao.SectionRepository;
import com.bupt.vo.ChannelSectionVo;
import com.bupt.vo.SysConst;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;

@Service
@Transactional
public class SectionService {


    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private SectionRepository sectionRepository;

    @Autowired
    private DeviceChannelRepository deviceChannelRepository;

    @Autowired
    private PrimaryKeyService primaryKeyService;

    //通过设备ID查询设备下的通道信息
    public List<ChannelSectionVo> channelSectionById(Integer deviceChannelId) {
        String sql = "SELECT channel_section_id,channel_index,section_name,section_index,start_position,\n" +
                " end_position,CASE WHEN STATUS=1 THEN '正常' ELSE '不正常' END AS STATUS,\n" +
                " CASE WHEN endpoint_switch=1 THEN '开通' ELSE '关闭' END AS endpoint_switch,ENDPOINT,endpoint_switch AS endpoint_switch_int  FROM channel_section_t WHERE device_channel_id="+deviceChannelId;
        Query query = entityManager.createNativeQuery(sql);
        List<ChannelSectionVo> channelSectionVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        if(channelSectionVoList.size()>0){
            //把对应值放到map里 直接key value获取
            HashMap<String, String> map = new HashMap<>();
            List<SysConst> sysConstList = this.endpoint();
            for (int i = 0; i <sysConstList.size() ; i++) {
                Map  sc= (Map)sysConstList.get(i);
                map.put(sc.get("const_value").toString(),sc.get("const_desc").toString());
            }
            System.out.println(map);

            for (int i = 0; i <channelSectionVoList.size() ; i++) {
                Map<String,Object>cs =(Map) channelSectionVoList.get(i);
                String endpointId = cs.get("ENDPOINT").toString();
                ArrayList<String> endpointList = new ArrayList<>();
                if(!endpointId.equals("")){
                    String[] split = endpointId.split(",");
                    for (int j = 0; j <split.length ; j++) {
                        endpointList.add(map.get(split[j]));
                    }
                    cs.put("ENDPOINT_CN",endpointList);
                }else{
                    cs.put("ENDPOINT_CN",endpointList);
                }
            }
        }


        return channelSectionVoList;
    }

    //通道区域信息添加页面
    public SectionResult add(Integer deviceChannelId, String sectionName, Float startPosition, Float endPosition,  int endpointSwitch,String endpoint) {
        ChannelSection channelSection = new ChannelSection();
        DeviceChannel deviceChannel = deviceChannelRepository.findByDeviceChannelId(deviceChannelId);
        if(deviceChannel!=null){
            int channelIndex = deviceChannel.getChannelIndex();
            Integer channel_section_id = primaryKeyService.getPrimaryKey("CHANNEL_SECTION_ID");
            channelSection.setChannelSectionId(channel_section_id);
            channelSection.setDeviceChannelId(deviceChannelId);
            channelSection.setChannelIndex(channelIndex);
            channelSection.setSectionName(sectionName);
            channelSection.setSectionIndex(new Random().nextInt(99));
            //这两个需要校验
            channelSection.setStartPosition(startPosition);
            channelSection.setEndPosition(endPosition);
            //通达最长米数
            Float channelLen = deviceChannel.getChannelLen();
            if(startPosition>endPosition){
                return new SectionResult(CommonCode.PARAMFAIL,new ChannelSection());
            }
            if(channelLen<endPosition){
                return new SectionResult(CommonCode.BEYONGDFAIL,new ChannelSection());
            }
            if(endPosition-startPosition>channelLen){
                return new SectionResult(CommonCode.BEYONGDFAIL,new ChannelSection());
            }
            //起始位置和结束位置 不能重复
            List<ChannelSection> allByDeviceChannelList = sectionRepository.findAllByDeviceChannelId(deviceChannelId);
            if(allByDeviceChannelList.size()>0){
                for (int i = 0; i <allByDeviceChannelList.size() ; i++) {
                    ChannelSection channelSection1 = allByDeviceChannelList.get(i);
                    Float startPosition1 = channelSection1.getStartPosition();
                    Float endPosition1 = channelSection1.getEndPosition();
                    if((startPosition<=startPosition1&&endPosition<=startPosition1)||(startPosition>=endPosition1&&endPosition>=endPosition1)){

                    }else{
                        return new SectionResult(CommonCode.EXISTFAIL,new ChannelSection());
                    }
                }
            }

            channelSection.setStatus(1);
            channelSection.setEndpoint(endpoint);
            channelSection.setEndpoint_switch(endpointSwitch);
//            channelSection.setLongitude(longitude);
//            channelSection.setLatitude(latitude);
//            channelSection.setEndLongitude(endLongitude);
//            channelSection.setEndLatitude(endLatitude);
//            channelSection.setDirection(direction);
            sectionRepository.save(channelSection);

            return new SectionResult(CommonCode.SUCCESS,channelSection);
        }else{
            return new SectionResult(CommonCode.NOTEXISTFAIL,new ChannelSection());
        }
    }

    //删除通道下的某个区域信息
    public Result deleteById(Integer channelSectionId) {
        Result result = new Result();
        ChannelSection channelSection= sectionRepository.findByChannelSectionId(channelSectionId);
        if(channelSection!=null){
            sectionRepository.deleteByChannelSectionId(channelSectionId);


            result.setResult("删除成功");
            return result;
        }
        result.setResult("删除失败");
        return result;
    }

    //通过IP修改单个区域信息
    public SectionResult editSectionById(Integer deviceChannelId,Integer channelSectionId, String sectionName, Float startPosition, Float endPosition,  int endpointSwitch,String endpoint) {
        ChannelSection byChannelSection = sectionRepository.findByChannelSectionId(channelSectionId);
        if (byChannelSection != null) {
            byChannelSection.setSectionName(sectionName);

            byChannelSection.setStartPosition(startPosition);
            byChannelSection.setEndPosition(endPosition);

            //起始位置和结束位置 不能重复
            List<ChannelSection> allByDeviceChannelList = sectionRepository.findAllByDeviceChannelId(deviceChannelId);
            if(allByDeviceChannelList.size()>0){
                for (int i = 0; i <allByDeviceChannelList.size() ; i++) {
                    ChannelSection channelSection1 = allByDeviceChannelList.get(i);
                    if(channelSection1.getChannelSectionId().equals(channelSectionId)){
                        continue;
                    }
                    Float startPosition1 = channelSection1.getStartPosition();
                    Float endPosition1 = channelSection1.getEndPosition();
                    if((startPosition<=startPosition1&&endPosition<=startPosition1)||(startPosition>=endPosition1&&endPosition>=endPosition1)){

                    }else{
                        return new SectionResult(CommonCode.EXISTFAIL,new ChannelSection());
                    }
                }
            }
            byChannelSection.setEndpoint_switch(endpointSwitch);
            if(endpointSwitch==1){
                byChannelSection.setEndpoint(endpoint);

            }else{
                byChannelSection.setEndpoint("");
            }

//            byChannelSection.setLongitude(channelSection.getLongitude());
//            byChannelSection.setLatitude(channelSection.getLatitude());
//            byChannelSection.setEndLongitude(channelSection.getEndLongitude());
//            byChannelSection.setEndLatitude(channelSection.getEndLatitude());
//            byChannelSection.setDirection(channelSection.getDirection());

        }

        ChannelSection save = sectionRepository.save(byChannelSection);
        if (save != null) {
            SectionResult sectionResult = new SectionResult(CommonCode.SUCCESS, byChannelSection);
            return sectionResult;
        }
        return new SectionResult(CommonCode.FAIL, null);
    }


    //报警端点
    public List<SysConst> endpoint() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ENDPOINT'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }
}
